/***************************************************************************
 *   Copyright (C) 2009 by Dead_Body                                       *
 *   jamesholodnak@gmail.com                                               *
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 *   This program is distributed in the hope that it will be useful,       *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
 *   GNU General Public License for more details.                          *
 *                                                                         *
 *   You should have received a copy of the GNU General Public License     *
 *   along with this program; if not, write to the                         *
 *   Free Software Foundation, Inc.,                                       *
 *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
 ***************************************************************************/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "pce/pce.h"
#include "pce/rom.h"
#include "system/system.h"
#include "gui2/gui2.h"
#include "log.h"
//#include "misc.h"
#ifdef SDL
#include <SDL/SDL.h>
#endif
#ifdef WIN32
#include <windows.h>
#endif

u8 *screen;					//640x480 pce screen buffer

int gui_active = 0;

//is the emulator currently executing the pce?
int running = 1;

//is it time to quit?
int quit = 0;

char curdir[1024];		//base directory for storage (config, states, bios, etc)
char path_config[1024];	//path to configuration file (set by config_defaults() or
config_t config;			//                  some other system dependent init call)

//currently loaded rom
static rom_t *rom;

int loadrom(char *fn)
{
	log_message("loading rom '%s'...\n",fn);

	if((rom = rom_load(fn)) == 0) {
		log_error("cannot load rom '%s'\n",fn);
		return(1);
	}
	pce_load(rom);
	return(0);
}

void unloadrom()
{

}

void loadstate()
{

}

void savestate()
{

}

int pceemu_init()
{
	init_system();
	file_init();
	log_init();
	config_load();
	video_init();
	gui2_init();
	gui_draw_setscreensize(512,480);
	gui_draw_setscreen((u8*)screen,512);
	filesystem_init();
	input_init();
	sound_init();
	config_save();
	return(0);
}

void pceemu_kill()
{
	config_save();
	unloadrom();
	filesystem_kill();
	gui2_kill();
	sound_kill();
	input_kill();
	log_message("killing video\n");
	video_kill();
	log_message("killing log!!\n");
	log_kill();
	file_kill();
	kill_system();
}

#ifdef WIN32GUI
#ifdef main
#undef main
#error rrrr
#endif
#define main console_main
#endif

//int main(int argc,char *argv[])
int main(int argc,char *argv[])
{
	char *p,*rom_filename = 0;
	int i;
	char str[1024];

	log_message("pceemu - version "VERSION"\n\n");

	//set running state to starting up
	running = -1;

	//zero out curdir
	memset(curdir,0,1024);

	//determine data directory
#if (defined(LINUX) || defined(OSX))
	if((p = getenv("HOME"))) {
		sprintf(curdir,"%s/.pceemu",p);
		mkdir(curdir);
	}
#elif defined(WIN32)
//TODO: win32 target can use documents and settings folder, to be like
//the cool kids, if it fails to exist, it can default on the argv0 method.
//	strcpy(curdir,argv[0]);

	GetModuleFileNameA(GetModuleHandle(0),str,1024);
	printf("module fn = '%s'\n",str);
#endif
	log_message("using pceemu data directory '%s'\n",curdir);

	//screen buffer
	screen = (u8*)malloc(512 * (480 + 16) * sizeof(u8));

	//clear screen
	memset(screen,0,512 * (480 + 16) * sizeof(u8));

	//initialize system
	pceemu_init();

	//parse command line arguments
	for(i=1;i<argc;i++) {
		if(strcmp("--windowed",argv[i]) == 0)
			config.windowed = 1;
		else
			rom_filename = argv[i];
	}

	//initialize pce
	pce_init();

	//if a rom filename was passed and that rom is loaded ok
	if(rom_filename && (loadrom(rom_filename) == 0)) {
		//set gui to inactive, running set to yes, hard reset, start sound playing
		gui_active = 0;
		running = 0;
		log_message("rom loaded ok, resetting and starting game\n");
		pce_reset(1);
		sound_play();
	}

	//else activate the gui and stop the sound
	else {
		gui_active = 1;
		sound_pause();
	}

	//start the main loop
	while(quit == 0) {
		//poll the input
		input_poll();

		//check os events
		check_events();

		//poll gui input
		gui2_poll();

		//if the gui is active, draw it
		if(gui_active) {
			gui2_draw(((u8*)screen),512);
			video_update(screen,512);
		}

		//or if a rom is loaded and the running state is positive
		else if(pce->rom && running) {
			if(pce_frame() == 1) {
				unloadrom();
				gui_active = 1;
			}
		}
	}

	//shutdown and exit
	unloadrom();
	pce_kill();
	pceemu_kill();
	free(screen);
	return(0);
}
